var token = null;
var showLoginPage = null;
var client_id = null;
var ws = null;
// 连接服务端
function connect() {
    token = isEmpty(token) ? $.cookie('token') : token;
    if (isEmpty(token)) {
        location.href = '/index/index';
    }
    // 创建websocket
    ws = new WebSocket("ws://127.0.0.1:7272?token="+token); // 连接时携带token
    ws.onmessage = onmessage;
    ws.onclose = function() {
        console.log("连接关闭，定时重连");
        connect();
    };
    ws.onclose = function() {
        console.log("连接关闭，定时重连");
        connect();
    };
    ws.onerror = function() {
        console.log("出现错误");
    };
}

// 当服务端发起消息时
function onmessage(e) {
    var data = JSON.parse(e.data);
    var fullData = data;
    data = data.data;
    switch(data.type){
        case 'login':
            // 当前用户有房间则显示进入入口，否则显示创建入口
            if (data.room_id > 0) {
                $('.create_room .join_room').attr('data-room-id',data.room_id);
                $('.create_room .join_room').show();
                $('.do_create_room').hide();
            } else {
                $('.create_room .join_room').hide();
                $('.do_create_room').show();
            }
            client_id = data.client_id;
            // 房间列表更新
            $('.room_list').empty();
            var roomDom = '';
            $.each(data.room_list,function(i,val) {
                roomDom += '<a href="/index/joinRoom?room_id='+val.id+'">'+val.room_name+'</a><br/><br/>';
            });
            $('.room_list').append(roomDom);
            break;
        case 'join':
            $('.onlineNum').text(data.online_num);
            // 重新渲染房间列表
            $('.online_user_list').empty();
            var onlineUserDom = '';
            $.each(data.online_list, function(i,val){
                onlineUserDom += '<div class="pos">' +
                    '<span class="identity">用户'+(i+1)+'：</span>' +
                    '<span class="nickname">'+val.nickname+' 已加入</span>' +
                    '</div>'
            });
            $('.online_user_list').append(onlineUserDom);
            break;
        case 'send_msg':
            var msgDom = '';
            msgDom += '<p class="content">'+data.send_user_nickname+' 说：'+data.send_content+'</p>';
            $('.msg_content').append(msgDom);
            break;
        case 'login_error':
            showLogin();
            break;
        default:
            break;
    }
}


// 判断obj是否为空获取非
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == ""){
        return true;
    }else{
        return false;
    }
}

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}